//
//  LyricUtils.m
//  爱MV
//
//  Created by 陈超 on 16/1/21.
//  Copyright © 2016年 cc. All rights reserved.
//

#import "LyricUtils.h"

@implementation LyricUtils
+(NSArray *)convertLyricUrlToArray:(NSData *)lyricData{
    NSData *data=lyricData;
    
    NSString *lyricContent=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    NSArray *array;
//    lyricContent=[lyricContent stringByReplacingOccurrencesOfString:@" " withString:@""];
    lyricContent=[lyricContent stringByReplacingOccurrencesOfString:@"\r\n" withString:@"\n"];
    array=[lyricContent componentsSeparatedByString:SPLICER];
    
    if(array&&array.count>1){
        lyricContent=[array objectAtIndex:1];
    }else {
        NSLog(@"歌词格式有误,请检查");
        return nil;
    }
    
    array=[lyricContent componentsSeparatedByString:RETURNKEY];
    
    NSMutableArray *resultArray=[[NSMutableArray alloc] init];
    
    [array enumerateObjectsUsingBlock:^(NSString * str, NSUInteger idx, BOOL * _Nonnull stop) {
        if(idx>=array.count-1){//最后一行
            *stop=YES;
        }else {
            
            if(str!=nil&&![str isEqual:@""]){
                NSArray *_arr=[str componentsSeparatedByString:@"]"];
                
                if(_arr&&_arr.count>0){
                    NSString *timeString=(NSString *)_arr[0];
                    NSString *lyricContent;
                    if(_arr.count>1){
                        lyricContent=(NSString *)_arr[1];
                    }
                    timeString=[timeString stringByReplacingOccurrencesOfString:@"[" withString:@""];
                    
                    //timeString like 03:06.27
                    NSArray *timeArray=[timeString componentsSeparatedByString:@":"];
                    NSInteger mins=[(NSString *)[timeArray objectAtIndex:0] integerValue];
                    float seconds=[(NSString*)[timeArray objectAtIndex:1] floatValue];
                    
                    seconds=mins*60+seconds;
                    if(resultArray.count>0){
                        LyricItem *lastLyricItem=(LyricItem*)[resultArray lastObject];
                        if(lastLyricItem.duration==0.0f){
                            lastLyricItem.duration=seconds-lastLyricItem.startTime;
                        }
                    }
                    if(lyricContent==nil||[lyricContent isEqual:@""]){
                        NSLog(@"纯时间行");
                    }else {
                        LyricItem *lyricItem=[[LyricItem alloc] init];
                        
                        lyricItem.startTime=seconds;
                        lyricItem.content=lyricContent;
                        [resultArray addObject:lyricItem];
                    }
                    
                }else {
                    NSLog(@"纯时间行");
                }
            }else {
                NSLog(@"空行");
            }
        }
        
    }];
    return resultArray.copy;
}
@end
